const util = require('../../utils/util.js')

const compareVersion = util.compareVersion

var id
Page({
  onShareAppMessage() {
    return {
      title: 'editor',
      path: 'page/component/pages/editor/editor'
    }
  },

  data: {
    formats: {},
    bottom: 0,
    readOnly: false,
    placeholder: '开始记录...',
    showtb: false,
    upOrDown: 'up',
    animationData: {},
    content: '',
    title: ''
  },
  inputTitle: function(e){
     var that = this
     that.setData({
       title: e.detail.value
     })
    wx.getStorage({
      key: 'noteList',
      success(res) {
        //**没有id说明操作是新增 */
        if (id == undefined) {
          var timestamp = util.getNowTimestamp()
          id = timestamp
          var time = util.getNowMMDDhhmm()
          var cnt = {
            id: timestamp,
            title: e.detail.value,
            content: that.data.content,
            time: time
          }
          /**缓存中若内容没有数据就新建数组 */
          if(res.data.length==0)res.data=[]
          res.data.push(cnt)
          console.log(cnt)
          wx.setStorage({
            key: 'noteList',
            data: res.data
          })
        }
        else{
          /**有id说明是做是修改 */
          for (var i = 0; i < res.data.length; i++) {
            if (res.data[i].id == id) {
              res.data[i].title = e.detail.value
              wx.setStorage({
                key: 'noteList',
                data: res.data,
              })
            }
          }
        }
      }
    })
  },
  readOnlyChange() {
    this.setData({
      readOnly: !this.data.readOnly
    })
  },
  onLoad(option) {
    var that = this
    this.canUse = true
    wx.loadFontFace({
      family: 'Pacifico',
      source: 'url("https://sungd.github.io/Pacifico.ttf")',
      success: console.log
    })
    const {
      SDKVersion
    } = wx.getSystemInfoSync()

    if (compareVersion(SDKVersion, '2.7.0') >= 0) {
      //
    } else {
      this.canUse = false
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
    /**加载editor内容 */
    var that = this
    id = option.id;
    wx.getStorage({
      key: 'noteList',
      success(res) {
        for (var obj of res.data) {
          if (obj.id == id) {
            that.setData({
              content: obj.content,
              title: obj.title
            })
          }
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    /**将加载的内容放到editor中去 */
    var that = this
    setTimeout(function() {
      that.editorCtx.setContents({
        delta: that.data.content
      })
    }, 300)
  },

  onEditorReady() {
    const that = this
    wx.createSelectorQuery().select('#editor').context(function(res) {
      that.editorCtx = res.context
    }).exec()
  },

  undo() {
    this.editorCtx.undo()
  },
  redo() {
    this.editorCtx.redo()
  },
  format(e) {
    let { name, value } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)
  },

  onStatusChange(e) {
    const formats = e.detail
    this.setData({
      formats
    })
  },

  contentChange: function(e) {
    var that = this;
    console.log(e.detail.delta)
    /**放置改变后的内容到content变量里 */
    that.setData({
      content: e.detail.delta
    })
    wx.getStorage({
      key: 'noteList',
      success(res) {
        //**没有id说明操作是新增 */
        if (id == undefined) {
          var timestamp = util.getNowTimestamp()
          id = timestamp
          var time = util.getNowMMDDhhmm()
          var tt = (that.data.title)==''?'未命名':title
          var cnt = {
            id: timestamp,
            title: tt,
            content: e.detail.delta,
            time: time
          }
          /**缓存中若内容没有数据就新建数组 */
          if (res.data.length == 0) res.data = []
          res.data.push(cnt)
          wx.setStorage({
            key: 'noteList',
            data: res.data
          })
        }
        else {
          /**有id说明操作是修改 */
          for (var i = 0; i < res.data.length; i++) {
            if (res.data[i].id == id) {
              res.data[i].content = e.detail.delta
              wx.setStorage({
                key: 'noteList',
                data: res.data,
              })
            }
          }
        }
      }
    })
    // /**将改变的内容缓存 */
    // /**读取缓存 */
    // wx.getStorage({
    //   key: 'noteList',
    //   success(res) {
    //    for(var i=0;i<res.data.length;i++){
    //      if (res.data[i].id == id){
    //        res.data[i].content = that.data.content
    //        wx.setStorage({
    //          key: 'noteList',
    //          data: res.data,
    //        })
    //      }
    //    }
    //   }
    // })
  
  },

  insertDivider() {
    this.editorCtx.insertDivider({
      success() {
        console.log('insert divider success')
      }
    })
  },
  clear() {
    this.editorCtx.clear({
      success() {
        console.log('clear success')
      }
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  insertImage() {
    const that = this
    wx.chooseImage({
      count: 1,
      success() {
        that.editorCtx.insertImage({
          src: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1543767268337&di=5a3bbfaeb30149b2afd33a3c7aaa4ead&imgtype=0&src=http%3A%2F%2Fimg02.tooopen.com%2Fimages%2F20151031%2Ftooopen_sy_147004931368.jpg',
          data: {
            id: 'abcd',
            role: 'god'
          },
          success() {
            console.log('insert image success')
          }
        })
      }
    })
  },
  showToolbar: function() {
    // 用that取代this，防止不必要的情况发生
    var that = this;
    // 创建一个动画实例
    var animation = wx.createAnimation({
      // 动画持续时间
      duration: 500,
      // 定义动画效果，当前是匀速
      timingFunction: 'ease'
    })
    // 将该变量赋值给当前动画
    that.animation = animation
    // 先在y轴偏移，然后用step()完成一个动画
    animation.translateY(200).step()
    // 用setData改变当前动画
    that.setData({
      // 通过export()方法导出数据
      animationData: animation.export(),
      // 改变view里面的Wx：if
      // showtb: true
    })
    if (!that.data.showtb) {
      that.setData({
        showtb: !that.data.showtb,
        upOrDown: 'up'
      })
    } else {
      that.setData({
        showtb: !that.data.showtb,
        upOrDown: 'down'
      })
    }
    // 设置setTimeout来改变y轴偏移量，实现有感觉的滑动
    setTimeout(function() {
      animation.translateY(0).step()
      that.setData({
        animationData: animation.export()
      })
    }, 200)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },
  deleteNote: function(){
    wx.getStorage({
      key: 'noteList',
      success(res) {
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].id == id) {
            res.data.splice(i,1)
            wx.setStorage({
              key: 'noteList',
              data: res.data,
            })

            wx.navigateBack({
              delta: 1
            })
          }
        }
      }
    })
  }
})